package com.qujia.customer.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qujia.common.annotation.Log;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.customer.domain.ActivityMessagePushRecord;
import com.qujia.customer.domain.CustomerCardSetting;
import com.qujia.customer.domain.CustomerCardSettingDetail;
import com.qujia.customer.domain.CustomerCardSettingDetailContent;
import com.qujia.customer.service.ActivityMessagePushRecordService;
import com.qujia.customer.service.CustomerCardSettingDetailContentService;
import com.qujia.customer.service.ICustomerCardSettingDetailService;
import com.qujia.customer.service.ICustomerCardSettingService;

import com.qujia.system.domain.SysEnterpriseUser;
import com.qujia.system.domain.SysStationUser;
import com.qujia.system.domain.vo.SysEnterpriseAndStationVo;
import com.qujia.system.service.ISysEnterpriseUserService;
import com.qujia.system.service.ISysStationUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户电子会员卡充值优惠设置明细Controller
 *
 * @author qujia
 * @date 2021-04-06
 */
@Api("充值活动接口")
@RestController
@RequestMapping("/customer/detail")
public class CustomerCardSettingDetailController extends BaseController
{
    @Autowired
    private ICustomerCardSettingDetailService customerCardSettingDetailService;
    @Autowired
    private ICustomerCardSettingService customerCardSettingService;
    @Autowired
    private CustomerCardSettingDetailContentService customerCardSettingDetailContentService;

    @Autowired
    private ActivityMessagePushRecordService activityMessagePushRecordService;

    @Autowired
    private ISysEnterpriseUserService sysEnterpriseUserService;

    @Autowired
    private ISysStationUserService stationUserService;


    /**
     * 查询客户电子会员卡充值优惠设置明细列表
     */
    @GetMapping("/list")
    @ApiOperation("查询客户电子会员卡充值优惠设置明细列表")
    public TableDataInfo list(CustomerCardSettingDetail customerCardSettingDetail)
    {
        LoginUser current=SecurityUtils.getLoginUser();
        if (SecurityUtils.isPartner()) {
            SysEnterpriseAndStationVo itemIds = stationUserService.getItemIds(current.getUser());
            if (itemIds != null){
                if(CollectionUtil.isEmpty(itemIds.getEnterpriseIds()) && CollectionUtil.isEmpty(itemIds.getStationIdsStr())){
                    return getDataTable(new ArrayList<>());
                }
                customerCardSettingDetail.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
                customerCardSettingDetail.setStationIdList(itemIds.getStationIdsStr());
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }else {
            if(StringUtils.equals(UserConstants.LEVEL_THREE,current.getUser().getUserLevel())){
                customerCardSettingDetail.setStationId(current.getUser().getStationId());
            }
            if(customerCardSettingDetail.getEnterpriseId()==null){
                customerCardSettingDetail.setEnterpriseId(current.getUser().getEnterpriseId());
            }
        }
        customerCardSettingDetail.setDelFlag("0");
        startPage();
        List<CustomerCardSettingDetail> detailList = customerCardSettingDetailService.selectCustomerCardSettingDetailList(customerCardSettingDetail);
        return getDataTable(detailList);
    }

    /**
     * 查询客户电子会员卡充值优惠设置明细列表
     */
//    @GetMapping("/listDetailInfo")
//    public TableDataInfo listDetailInfo(CustomerCardSettingDetail customerCardSettingDetail)
//    {
//        startPage();
//        List<CustomerCardSettingDetail> list = customerCardSettingDetailService.listDetailInfo(customerCardSettingDetail);
//        return getDataTable(list);
//    }
    @GetMapping("/listDetailInfo")
    public TableDataInfo listDetailInfo(CustomerCardSetting customerCardSetting)
    {
        startPage();
        LoginUser currentUser = SecurityUtils.getLoginUser();
//        SysDept dept =new SysDept();
//        dept.setDeptId(currentUser.getUser().getDeptId());
//        List<String> list = deptService.selectDeptId(dept);
//        if(list!=null && list.size()>0){
//            customerCardSetting.setStationIdList(list);
//            customerCardSetting.setStationId(null);
//        }

        customerCardSetting.setStationId(currentUser.getUser().getDeptId());
        customerCardSetting.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        customerCardSetting.setDelFlag("0");
        List<CustomerCardSettingDetail> detailList = customerCardSettingDetailService.listDetailInfo(customerCardSetting);
        return getDataTable(detailList);
    }
    /**
     * 获取客户电子会员卡充值优惠设置明细详细信息
     */
    @ApiOperation("获取客户电子会员卡充值优惠设置明细详细信息")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        CustomerCardSettingDetail customerCardSettingDetail = customerCardSettingDetailService.selectCustomerCardSettingDetailById(id);

        CustomerCardSettingDetailContent customerCardSettingDetailContent=new CustomerCardSettingDetailContent();
        customerCardSettingDetailContent.setCcsdId(id);
        List<CustomerCardSettingDetailContent> list=customerCardSettingDetailContentService.query(customerCardSettingDetailContent);
        for (CustomerCardSettingDetailContent detailContent : list) {
            String couponIssueIds = detailContent.getCouponIssueIds();
            if(StringUtils.isNotEmpty(couponIssueIds)){
                String[] split = couponIssueIds.split(",");
                List<String> ids=new ArrayList<>(Arrays.asList(split));
                detailContent.setCouponIssueId(ids);
            }
        }
        customerCardSettingDetail.setContentList(list);
        ActivityMessagePushRecord pushRecord=new ActivityMessagePushRecord();
        pushRecord.setBusinessId(customerCardSettingDetail.getId());
        pushRecord.setBusinessName(ActivityMessagePushRecord.CUSTOMER_CARD_SETTING_DETAIL);
        List<ActivityMessagePushRecord> records=activityMessagePushRecordService.query(pushRecord);
        if(records.size()>0){
            ActivityMessagePushRecord record = records.get(0);
            customerCardSettingDetail.setSendFlag(record.getSendFlag());
            customerCardSettingDetail.setWxContent(record.getContent());
        }else{
            customerCardSettingDetail.setSendFlag(0);
        }
        return AjaxResult.success(customerCardSettingDetail);
    }

    /**
     * 新增客户电子会员卡充值优惠设置明细
     */
    @ApiOperation("新增客户电子会员卡充值优惠设置明细")
    @Log(title = "客户电子会员卡充值优惠设置明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CustomerCardSettingDetail customerCardSettingDetail)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        if(customerCardSettingDetail.getEnterpriseId()==null){
            customerCardSettingDetail.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        }
        CustomerCardSetting customerCardSetting=new  CustomerCardSetting();
        customerCardSetting.setEnterpriseId(customerCardSettingDetail.getEnterpriseId());
        customerCardSetting.setDelFlag("0");
        List<CustomerCardSetting> customerCardSettings=customerCardSettingService.selectCustomerCardSettingList(customerCardSetting);
        if(customerCardSettings==null||customerCardSettings.size()==0){
            return AjaxResult.error("该油站请先设置电子卡规则");
        }
        customerCardSettingDetail.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_RECHARGE);
      if (isHasIntersection(customerCardSettingDetail)) {
            return AjaxResult.error("已存在相同充值赠额条件");
        }

        customerCardSettingDetail.setParentId(customerCardSettings.get(0).getId());
        customerCardSettingDetail.setStatus(CustomerCardSettingDetail.SETTING_STATUS_NORMAL);
        int i = customerCardSettingDetailService.insertCustomerCardSettingDetail(customerCardSettingDetail);
        activityMessagePushRecordService.sendWxMessage(customerCardSettingDetail.getId(),ActivityMessagePushRecord.CUSTOMER_CARD_SETTING_DETAIL,customerCardSettingDetail.getWxContent(),customerCardSettingDetail.getSendFlag());
        return toAjax(i);
    }

    /**
     * 新增客户电子会员卡充值优惠设置明细
     */
    @ApiOperation("新增客户电子会员卡消费返额设置")
    @Log(title = "客户电子会员卡消费返额设置", businessType = BusinessType.INSERT)
    @PostMapping("/addConsumeActivity")
    public AjaxResult addConsumeActivity(@RequestBody CustomerCardSettingDetail customerCardSettingDetail)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        if(customerCardSettingDetail.getEnterpriseId()==null){
            customerCardSettingDetail.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        }
        CustomerCardSetting customerCardSetting=new  CustomerCardSetting();
        customerCardSetting.setEnterpriseId(customerCardSettingDetail.getEnterpriseId());
        customerCardSetting.setDelFlag("0");
        List<CustomerCardSetting> customerCardSettings=customerCardSettingService.selectCustomerCardSettingList(customerCardSetting);
        if(customerCardSettings==null||customerCardSettings.size()==0){
            return AjaxResult.error("该油站请先设置电子卡规则");
        }
        customerCardSettingDetail.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_CONSUME);
        if (isHasIntersection(customerCardSettingDetail)) {
            return AjaxResult.error("已存在相同充值赠额条件");
        }

        customerCardSettingDetail.setParentId(customerCardSettings.get(0).getId());
        customerCardSettingDetail.setStatus(CustomerCardSettingDetail.SETTING_STATUS_NORMAL);
        customerCardSettingDetail.setPayType("dzk_wx");

        customerCardSettingDetail.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE);

        int i = customerCardSettingDetailService.insertCustomerCardSettingDetail(customerCardSettingDetail);
        //activityMessagePushRecordService.sendWxMessage(customerCardSettingDetail.getId(),ActivityMessagePushRecord.CUSTOMER_CARD_SETTING_DETAIL,customerCardSettingDetail.getWxContent(),customerCardSettingDetail.getSendFlag());
        return toAjax(i);
    }

    public boolean isHasIntersection2(CustomerCardSettingDetail customerCardSettingDetail){
        boolean hasIntersection = false;
        List<CustomerCardSettingDetailContent> contentList = customerCardSettingDetail.getContentList();
        if(contentList.size()>1){
            for (int i = 0; i < contentList.size(); i++) {
                CustomerCardSettingDetailContent detailContent = contentList.get(i);
                BigDecimal inputStart = detailContent.getRechargeAmtLowerLimit();
                BigDecimal inputEnd = detailContent.getRechargeAmtUpperLimit();
                for (int j=i+1; j < contentList.size(); j++) {
                    CustomerCardSettingDetailContent content = contentList.get(j);
                    BigDecimal detailStart = content.getRechargeAmtLowerLimit();
                    BigDecimal detailEnd = content.getRechargeAmtUpperLimit();
                    // 判断完全包含的情况
                    if (detailStart.compareTo(inputStart) <= 0 && detailEnd.compareTo(inputEnd) >= 0) {
                        hasIntersection = true;
                        break;
                    }

                    // 判断部分包含（上限相交）的情况
                    if (detailEnd.compareTo(inputStart) > 0 && detailEnd.compareTo(inputEnd) <= 0) {
                        hasIntersection = true;
                        break;
                    }

                    // 判断部分包含（下限相交）的情况
                    if (detailStart.compareTo(inputStart) >= 0 && detailStart.compareTo(inputEnd) < 0) {
                        hasIntersection = true;
                        break;
                    }
                }
            }

        }
        return hasIntersection;

    }

    public boolean isHasIntersection(CustomerCardSettingDetail customerCardSettingDetail){
        if(isHasIntersection2(customerCardSettingDetail)){
            //比较自身是否有重合
            return true;
        }
//判断是否重复添加
        CustomerCardSettingDetail newcustomerCardSettingDetail = new CustomerCardSettingDetail();
        //油企、油站、电子卡类型
        newcustomerCardSettingDetail.setEnterpriseId(customerCardSettingDetail.getEnterpriseId());
        newcustomerCardSettingDetail.setStationId(customerCardSettingDetail.getStationId());
        newcustomerCardSettingDetail.setCardType(customerCardSettingDetail.getCardType());
        newcustomerCardSettingDetail.setActivityMode(customerCardSettingDetail.getActivityMode());
        newcustomerCardSettingDetail.setActivityType(customerCardSettingDetail.getActivityType());
        newcustomerCardSettingDetail.setAccordingTo(customerCardSettingDetail.getAccordingTo());
        newcustomerCardSettingDetail.setDelFlag("0");


        List<CustomerCardSettingDetail> detailList = customerCardSettingDetailService.selectCustomerCardSettingDetailList(newcustomerCardSettingDetail);
        if(customerCardSettingDetail.getId()!=null){
            detailList =detailList.stream().filter(detail->!detail.getId().equals(customerCardSettingDetail.getId())).collect(Collectors.toList());
        }


        List<CustomerCardSettingDetailContent> contentList=new ArrayList<>();
        for (CustomerCardSettingDetail cardSettingDetail : detailList) {
            CustomerCardSettingDetailContent detailContent=new CustomerCardSettingDetailContent();
            detailContent.setCcsdId(cardSettingDetail.getId());
            List<CustomerCardSettingDetailContent> query = customerCardSettingDetailContentService.query(detailContent);
            contentList.addAll(query);
        }
        boolean hasIntersection = false;


        List<CustomerCardSettingDetailContent> inputContentList = customerCardSettingDetail.getContentList();
        for (CustomerCardSettingDetailContent detailContent : inputContentList) {
            BigDecimal inputStart = detailContent.getRechargeAmtLowerLimit();
            BigDecimal inputEnd = detailContent.getRechargeAmtUpperLimit();
            for (CustomerCardSettingDetailContent content : contentList) {
                BigDecimal detailStart = content.getRechargeAmtLowerLimit();
                BigDecimal detailEnd = content.getRechargeAmtUpperLimit();

                // 判断完全包含的情况
                if (detailStart.compareTo(inputStart) <= 0 && detailEnd.compareTo(inputEnd) >= 0) {
                    hasIntersection = true;
                    break;
                }

                // 判断部分包含（上限相交）的情况
                if (detailEnd.compareTo(inputStart) > 0 && detailEnd.compareTo(inputEnd) <= 0) {
                    hasIntersection = true;
                    break;
                }

                // 判断部分包含（下限相交）的情况
                if (detailStart.compareTo(inputStart) >= 0 && detailStart.compareTo(inputEnd) < 0) {
                    hasIntersection = true;
                    break;
                }
            }
        }
        return hasIntersection;
    }


    /**
     * 修改客户电子会员卡充值优惠设置明细
     */
    @Log(title = "客户电子会员卡充值优惠设置明细", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    @ApiOperation("修改客户电子会员卡充值优惠设置明细")
    public AjaxResult edit(@RequestBody CustomerCardSettingDetail customerCardSettingDetail)
    {
        CustomerCardSetting customerCardSetting=new  CustomerCardSetting();
        customerCardSetting.setEnterpriseId(customerCardSettingDetail.getEnterpriseId());
        customerCardSetting.setDelFlag("0");
        List<CustomerCardSetting> customerCardSettings=customerCardSettingService.selectCustomerCardSettingList(customerCardSetting);
        if(customerCardSettings==null||customerCardSettings.size()==0){
            return AjaxResult.error("该油站请先设置电子卡规则");
        }
        if (isHasIntersection(customerCardSettingDetail)) {
            return AjaxResult.error("已存在相同充值赠额条件");
        }
        int i=0;
        CustomerCardSettingDetail customerCardSettingDetail1=new CustomerCardSettingDetail();
        customerCardSettingDetail1.setId(customerCardSettingDetail.getId());
        customerCardSettingDetail1.setDelFlag("1");

        CustomerCardSettingDetail settingDetail = customerCardSettingDetailService.selectCustomerCardSettingDetailById(customerCardSettingDetail.getId());
        //先进行逻辑删除
        i= customerCardSettingDetailService.updateCustomerCardSettingDetail(customerCardSettingDetail1);
        CustomerCardSettingDetailContent detailContent=new CustomerCardSettingDetailContent();
        detailContent.setCcsdId(customerCardSettingDetail.getId());
        detailContent.setDelFlag(1);
        i=i+customerCardSettingDetailContentService.updateByCcsdId(detailContent);
        customerCardSettingDetail.setId(null);
        customerCardSettingDetail.setStatus(settingDetail.getStatus());
        customerCardSettingDetail.setParentId(customerCardSettings.get(0).getId());
        return toAjax(customerCardSettingDetailService.insertCustomerCardSettingDetail(customerCardSettingDetail));
    }

    /**
     * 逻辑删除油站信息
     */
    @Log(title = "逻辑删除油站信息", businessType = BusinessType.DELETE)
    @PostMapping(value = "/deleteDetail")
    public AjaxResult deleteDetail(@RequestBody CustomerCardSettingDetail detail )
    {
        CustomerCardSettingDetail customerCardSettingDetail=new CustomerCardSettingDetail();
        customerCardSettingDetail.setDelFlag("1");
        customerCardSettingDetail.setId(detail.getId());

        CustomerCardSettingDetailContent detailContent=new CustomerCardSettingDetailContent();
        detailContent.setCcsdId(customerCardSettingDetail.getId());
        detailContent.setDelFlag(1);
        customerCardSettingDetailContentService.updateByCcsdId(detailContent);

        return toAjax(customerCardSettingDetailService.updateCustomerCardSettingDetail(customerCardSettingDetail));
    }



    /**
     * 逻辑删除油站信息
     */
    @Log(title = "逻辑删除油站信息", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/deleteDetails/{ids}")
    @ApiOperation("逻辑删除油站信息")
    public AjaxResult deleteDetails(@PathVariable Long[] ids)
    {
        int i=0;
        for (Long id : ids) {
            CustomerCardSettingDetail customerCardSettingDetail=new CustomerCardSettingDetail();
            customerCardSettingDetail.setDelFlag("1");
            customerCardSettingDetail.setId(id);

            CustomerCardSettingDetailContent detailContent=new CustomerCardSettingDetailContent();
            detailContent.setCcsdId(customerCardSettingDetail.getId());
            detailContent.setDelFlag(1);
            customerCardSettingDetailContentService.updateByCcsdId(detailContent);
            i=i+customerCardSettingDetailService.updateCustomerCardSettingDetail(customerCardSettingDetail);
        }


        return toAjax(i);
    }

    /**
     * 删除客户电子会员卡充值优惠设置明细
     */
    @Log(title = "客户电子会员卡充值优惠设置明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(customerCardSettingDetailService.deleteCustomerCardSettingDetailByIds(ids));
    }

    /**
     * 更新充值活动状态
     */
    @Log(title = "更新充值活动状态")
    @GetMapping("/updateStatus/{status}/{ids}")
    @ApiOperation("更新充值活动状态")
    public AjaxResult updateStatus(@PathVariable("status") String status,@PathVariable("ids") Long[] ids){
        Integer i=customerCardSettingDetailService.updateStatus(status,ids);
        return toAjax(i);
    }
}
